'''
@Author: your name
@Date: 2020-03-02 09:42:09
@LastEditTime: 2020-03-03 10:42:37
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /permcomp/comparison/forms.py
'''
import re

from django import forms


class CompTextForm(forms.Form):
    perm_text = forms.CharField(label='申请权限列表',
                                    widget=forms.Textarea(attrs={
                                        "id":          "perm-text",
                                        "class":       "permission-text",
                                        "placeholder": "在这里填写敏感权限声明文本",
                                        "wrap":         "off"
                                    }))
    desc_text = forms.CharField(label='权限描述文本',
                                    widget=forms.Textarea(attrs={
                                        "id":          "perm-list",
                                        "class":       "permission-list",
                                        "placeholder": "在这里填写 APP 中出现的权限，每行一个权限",
                                        "wrap":         "off"
                                    }))

    def clean(self):
        cleaned_data = self.cleaned_data
        cleaned_data['desc_text'] = cleaned_data['desc_text'].replace('\r', '').replace('\n', '')
        perm_text = cleaned_data['perm_text']
        perm_set = set()
        regex = r"(?:uses-permission:name='(.*)'|permission:(.*))"
        for line in perm_text.split("\n"):
            line = line.replace(" ", "").replace("\r", "")
            matched_strs = re.finditer(regex, line)
            for matched_str in matched_strs:
                if matched_str.group(1) is not None:
                    perm_set.add(matched_str.group(1))
                    break
                elif matched_str.group(2) is not None:
                    perm_set.add(matched_str.group(2))
                    break
            else:
                if len(line.split(".")) > 2 and line.startswith("android.permission."):
                    perm_set.add(line)

        cleaned_data['perm_set'] = perm_set
        self.cleaned_data = cleaned_data

        return cleaned_data
